package com.kkwrite.regimen.consumer.common;

import com.kkwrite.regimen.consumer.config.SystemConfig;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;

/**
 * Created by lisha on 2018/7/31 20:50.
 *
 * @author lisha
 */
@Component("myHttpClient")
public class HttpClientUtil {

    @Resource(name = "systemConfig")
    private SystemConfig config;

    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
    private static final char[] STORE_KEY = "1508479641".toCharArray();
    private RestTemplate restTemplate;

    @PostConstruct
    public void init() {
        logger.info("===========HttpClientUtil开始初始化===========");
        String storeFilePath = config.getPayCertificateStoreFilePath();
        SSLConnectionSocketFactory sslsf;
        try {
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            FileInputStream inputStream = new FileInputStream(new File(storeFilePath));
            keyStore.load(inputStream, STORE_KEY);
            inputStream.close();
            SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, STORE_KEY).build();
            sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, null,
                    SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
        HttpComponentsClientHttpRequestFactory requestFactory =
                new HttpComponentsClientHttpRequestFactory(httpClient);

        restTemplate = new RestTemplate(requestFactory);
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        logger.info("===========HttpClientUtil初始化完成===========");
    }

    public String post(String url, String data) {
        return restTemplate.postForObject(url, data, String.class);
    }

}
